package org.jiaxin.nutrient.controller;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.jiaxin.nutrient.bean.DietaryRecommendDaily;
import org.jiaxin.nutrient.bean.NutrientsInfo;
import org.jiaxin.nutrient.bean.NutritionWithVolume;
import org.jiaxin.nutrient.bean.UserInfo;
import org.jiaxin.nutrient.utils.CommonUtils;
import org.jiaxin.nutrient.utils.DBTemplate;
import org.jiaxin.nutrient.utils.DateTimeUtils;
import org.jiaxin.nutrient.utils.DietaryUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiaxin
 * @version 1.0
 * @description: TODO 用户关于饮食图谱的控制类
 * @date 2024/5/20 23:05
 */
@RestController
public class UserGraphController {
    private Logger logger= LoggerFactory.getLogger(UserGraphController.class);
    @RequestMapping("user/loadDietMap")
    public Map<String,Object> userGraph(@RequestParam String userName) throws Exception {
        logger.info("userName: {}",userName);
        //这里要读取用户的食谱信息，如果用户是新注册的用户没有食谱的话，返回空值
        DBTemplate<UserInfo> instance = DBTemplate.getInstance();
        String sql="select * from user_info where user_name='"+userName+"'";
        System.out.println("getUser "+sql);

        List<UserInfo> sqlData = instance.getSqlData(sql, UserInfo.class);
        System.out.println("userSize: "+sqlData.size());
        instance.close();
        for (UserInfo sqlDatum : sqlData) {
            //如果为空的话 返回
            if (StringUtils.isBlank(sqlDatum.getDietaryPrefer())){
                return CommonUtils.returnMap("饮食图谱为空，请您填写必要的问卷！",300);
            }else {
                    DBTemplate<DietaryRecommendDaily> dietaryRecommendDailyDBTemplate = DBTemplate.getInstance();
                    HashMap<String, Object> hashMap = new HashMap<>();
                    //查询 推荐图谱的记录表
                  String re_sql="select * from dietary_recommend_daily where user_name = '${user_name}' and date(update_time)= '${update_time}'";
                  re_sql=re_sql.replace("${user_name}",userName)
                          .replace("${update_time}", DateTimeUtils.getNowDate());

                List<DietaryRecommendDaily> dailyDBTemplateSqlData = dietaryRecommendDailyDBTemplate.getSqlData(re_sql, DietaryRecommendDaily.class);

                Map<String, DietaryRecommendDaily> dietaryRecommendDailyMap;


                if (dailyDBTemplateSqlData.isEmpty()){
                    //如果当日的 饮食图谱没有生成， 那么返回饮食图谱
                    dietaryRecommendDailyMap = DietaryUtils.getDietaryGraph(sqlDatum);
                    //写入到数据库
                    DietaryUtils.saveDietaryGraph(dietaryRecommendDailyDBTemplate,dietaryRecommendDailyMap,userName);
                }else {
                    //如果当日的饮食图谱已经生成了  那么 直接返回即可
                    /*Map<String,> dietaryGraph = new HashMap<>();*/
                    dietaryRecommendDailyMap=new HashMap<>();
                    for (DietaryRecommendDaily datum : dailyDBTemplateSqlData) {
                        if ("谷物及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("谷物及制品",datum);
                            }else if ("薯类、淀粉及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("薯类、淀粉及制品",datum);
                            }else if ("干豆类及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("干豆类及制品",datum);
                            }else if ("蔬菜及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("蔬菜及制品",datum);
                            }else if ("畜肉类及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("畜肉类及制品",datum);
                            }else if ("禽肉类及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("禽肉类及制品",datum);
                            }else if ("蛋类及制品".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("蛋类及制品",datum);
                            }else if ("鱼虾蟹贝类".equals(datum.getCate1())){
                            dietaryRecommendDailyMap.put("鱼虾蟹贝类",datum);
                            }
                    }

                }

                //System.out.println("dietaryGraph: "+dietaryGraph);
                //对食谱进行 格式化 nodes  edges
                JSONArray nodes = DietaryUtils.formatNodes(dietaryRecommendDailyMap, userName);
                JSONArray edges = DietaryUtils.formatEdge(dietaryRecommendDailyMap);
                System.out.println("nodes: "+nodes);
                System.out.println("edges: "+edges);
                hashMap.put("nodes",nodes);
                hashMap.put("edges",edges);
                hashMap.put("dietaryPrefer",sqlDatum.getDietaryPrefer());
                hashMap.put("status",200);
                hashMap.put("message","加载成功！");// ctrl+t
                return hashMap;
            }
        }
        return null;
    }

    @PostMapping("user/udpate")
    public Map<String,Object> update(@RequestBody UserInfo userInfo) throws Exception {
        String update="update user_info set gender='${gender}' " +
                ",dietary_prefer='${dietary_prefer}', update_time= '${update_time}' where user_name='${user_name}'";
        update=update.replace("${gender}",userInfo.getGender())
                .replace("${dietary_prefer}",userInfo.getDietaryPrefer())
                .replace("${update_time}",userInfo.getUpdateTime())
                .replace("${user_name}",userInfo.getUserName());
        System.out.println(update);


        DBTemplate<UserInfo> instance = DBTemplate.getInstance();
        try {
            instance.getConnection().prepareStatement(update).executeUpdate();
            instance.close();
            return CommonUtils.returnMap("提交成功！！！",200);
        }catch (Exception e){
            e.printStackTrace();
            instance.close();
            return CommonUtils.returnMap("提交失败"+e.getMessage(),300);
        }

    }



}
